package charlie.shop.web;

import charlie.shop.misc.Common;
import com.charlie.beans.Product;
import com.charlie.db.DAOLocal;
import com.charlie.sessions.ProductFacadeLocal;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Main page servlet
 * 
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@WebServlet(name = "MainServlet", urlPatterns = {"/"})
public class MainServlet extends HttpServlet {

    int items_limit = 9;
    int recommends_limit = 10;
    @EJB
    private ProductFacadeLocal productFacade;
    @EJB
    private DAOLocal dao;
    private Random rand;

    @Override
    public void init() throws ServletException {
        super.init();
        rand = new Random();
    }

    /**
     * Display start page with items
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int page = Common.getPage(request);
        int total_items = productFacade.count();
        int pages = (int) Math.ceil((float)total_items / (float)items_limit);

        List<Product> items = null;
        if (page <= pages) {
            items = dao.getProductRange((page - 1) * items_limit, page * items_limit);
        }

        request.setAttribute("items_list", items);
        request.setAttribute("total_items", total_items);
        request.setAttribute("page", page);
        request.setAttribute("pagesCount", pages);

        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
    }    
}
